package org.example.controller;


import lombok.extern.slf4j.Slf4j;
import org.example.controller.request.ShortLinkAddRequest;
import org.example.controller.request.ShortLinkDelRequest;
import org.example.controller.request.ShortLinkPageRequest;
import org.example.controller.request.ShortLinkUpdateRequest;
import org.example.service.LogService;
import org.example.service.ShortLinkService;
import org.example.util.JsonData;
import org.example.vo.ShortLinkVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 谢超
 * @since 2023-08-15
 */
@RestController
@Slf4j
@RequestMapping("/api/link/v1")
public class ShortLinkController {

    @Resource
    private ShortLinkService shortLinkService;

    @Value("${rpc.token}")
    private String rpcToken;

    @Resource
    private LogService logService;

    /**
     * 创建短链
     * @param request
     * @return
     */
    @PostMapping("add")
    public JsonData addShortLink(@RequestBody ShortLinkAddRequest request) {
        return shortLinkService.addShortLink(request);
    }

    /**
     * 分页查询
     * @param request
     * @return
     */
    @PostMapping("page")
    public JsonData pageByGroupId(@RequestBody ShortLinkPageRequest request) {
        Map<String, Object> result = shortLinkService.pageByGroupId(request);
        return JsonData.buildSuccess(result);
    }

    /**
     * 删除短链
     * @param request
     * @return
     */
    @PostMapping("del")
    public JsonData delLink(@RequestBody ShortLinkDelRequest request) {
        JsonData jsonData = shortLinkService.delLinkCode(request);
        return jsonData;
    }

    @PostMapping("update")
    public JsonData updateLink(@RequestBody ShortLinkUpdateRequest request) {
        JsonData jsonData = shortLinkService.updateLink(request);
        return jsonData;
    }

    @GetMapping("check")
    public JsonData check(@RequestParam("shortLinkCode") String shortLinkCode, HttpServletRequest request) {
        String token = request.getHeader("rpc-token");
        if (!rpcToken.equalsIgnoreCase(token)) {
            return JsonData.buildError("非法访问");
        }

        ShortLinkVO shortLinkVO = shortLinkService.parseShortLinkCode(shortLinkCode);

        return shortLinkVO == null ? JsonData.buildError("短链不存在") : JsonData.buildSuccess();
    }
}

